(function(T) {
	var serverUrl = window.location.origin;

	let sdk_name = "anyPortal";

	let WX;
	if(wx.config == undefined){
		WX = jWeixin;
	}else{
		WX = wx;
	}

	const getUrlParam = function (url, paraName)  {
		let arrObj = url.split("?");
		if (arrObj.length > 2) {
			let arrPara = arrObj[2].split("&")
			let arr;
			for (let i in arrPara) {
				arr = arrPara[i].split("=")
				if (arr != null && arr[0] == paraName) {
					return arr[1]
				}
			}
			return ""
		}
	}

	let redirectKey = ''
	if (window.location.href.split("?").length > 2) {
		console.log('-----', window.location.href)
		redirectKey = getUrlParam(window.location.href, 'redirectKey')
		console.log('-----', getUrlParam(window.location.href, 'redirectKey'))
	}
	console.log('-----redirectKey', redirectKey)
	console.log('===========serverUrl=======',serverUrl)
	console.log('------', window.location.href)
	let _anyPortal = new(function() {
		var _config;
		this.ready = function(param, func) {
			let url = window.location.href;
			if (url.indexOf("#") > -1) {
				url = url.split("#")[0];
				console.log('encodeURIComponent,', url)
			}
			url = encodeURIComponent(url);
			// 已 ? 在匹配一次
			//if (url.indexOf("?") > -1) {
			//	url = url.split("?")[0];
			//}

			let ajaxUrl =
				`${serverUrl}/zm/zmglpt-integration-web/mobile/signJsapi.do?redirectKey=${redirectKey}&signUrl=${url}&t=${new Date().getTime()}`

			console.log('ajaxUrl---', ajaxUrl)

			/**
			 * 钉钉初始化
			 */
			post_methods(
				ajaxUrl, {},
				function(data) {
					setTimeout(function() {
						_config = data.bean;
						console.log('---_config----', JSON.stringify(_config))

						anyPortal.config({
							// agentid: param.agentId,
							// corpid: _config.corpId,
							beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: _config.corpId, // 必填，企业微信的corpID
							timestamp: _config.timestamp,
							nonceStr: _config.nonceStr,
							signature: _config.signature,
							jsApiList: param.jsApiList,
							success: function(res) {
								// 回调
								console.log("success:", res)
							},
							fail: function(res) {
								console.log("fail:", res)
								if (res.errMsg.indexOf('function not exist') > - 1) {
									alert('版本过低请升级')
								}
							}
						});


						WX.error(function(err) {
							console.log('wx--err--')
							console.log("wx error: " + JSON.stringify(err));
							// alert(JSON.stringify(err))
						});
						WX.ready(function() {
							console.log('- wx ready start--');
							// WX.getLocation({
							// 	type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
							// 	success: function (res) {
							// 		console.log("getLocation:",res)
							// 	}
							// });

							func();
						});

					}, 1000);
				},
				function(err) {
					setTimeout(() => {
						console.log('----', err)
						let code = err.responseJSON.code;
						if (Number(code) === 500) {
							console.log('--------success- err------')
							// location.reload()
							// anyPortal.ready(param, func)
							// alert('鉴权错误！')

							console.log('--------success--- err----')
						}
					}, 500)
					//	alert(JSON.stringify(err))
				}
			)
		};

		//config
		this.config = function(data) {
			//beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
			//debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			console.log("isWorkWechat：", WX)
			// jWeixin.agentConfig(data);
			WX.config(data);
		};

		//error
		this.error = function(data) {
			console.log('adsadadahda')
			WX.error(data);
			console.log('adsadadassss----hda')
		};

		function isIOS() {
			return window.navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false;
		}

		function isAndroid() {
			return window.navigator.userAgent.match(/(Android)/i) ? true : false;
		}

		/**
		 * 获取用户信息
		 * @param param 钉钉提供的code
		 * @param func 方法对象
		 */
		this.getAccountInfo = function(param, func) {
			let ajaxUrl =
				`${serverUrl}/zm/zmglpt-integration-web/mobile/getAccountInfo.do?code=${param}&redirectKey=${redirectKey}&t=${new Date().getTime()}`
			console.log('ajaxUrl------getAccountInfo', ajaxUrl)
			post_methods(
				ajaxUrl, {},
				function(data) {
					if(data.success) {
						func.onSuccess(data)
					} else {
						// 一人多账号
						if(data.code  == 996) {
							func.onSuccess(data)
						} else {
							func.onFail(data.msg)
						}
					}
				},
				function(err) {
					func.onFail(err.responseJSON.msg || "请求失败")
				}
			)
		}

		this.saveAppAccountRel = function(param, func) {
			let ajaxUrl =
				`${serverUrl}/zm/zmglpt-integration-web/mobile/saveAppAccountRel.do?redirectKey=${redirectKey}&t=${new Date().getTime()}`
			let params = {
				"thirdPartyUuid": param.thirdPartyUuid,
				"accountUuid": param.accountUuid
			}
			console.log('ajaxUrl------saveAppAccountRel', ajaxUrl)
			console.log('ajaxUrl------params', param)
			console.log('ajaxUrl------saveAppAccountRel----------')
			post_methods(
				ajaxUrl,
				JSON.stringify(params),
				function(data) {
					func.onSuccess(data)
				},
				function(err) {
					func.onFail(err)
				}
			)
		}
	})

	function _setNameSpace(obj, rootName) {
		if (rootName && rootName !== "") {
			obj["_namespace"] = rootName;
		}
		for (const key in obj) {
			let type = typeof obj[key];
			if (type === "object") {
				//console.log("object:", key);
				obj[key]["_namespace"] = (obj["_namespace"] ? obj["_namespace"] : "") + "." + key;
				_setNameSpace(obj[key]);
			} else if (type === "function") {
				obj[key]["_fullName"] = obj["_namespace"] + "." + key;
				//console.log("function:", key);
				//console.log("_fullName:", obj["_namespace"] + "." + key);
			}
		}
	}
	_setNameSpace(_anyPortal, sdk_name);


	const _handler = {
		get(target, key) {
			console.log(target, key)
			if (typeof target[key] === "object") {
				return new Proxy(target[key], _handler);
			} else if (typeof target[key] === "function") {
				return new Proxy(target[key], {
					apply(t, ctx, args) {
						let fnFullName = target[key]["_fullName"];
						let result = Reflect.apply(...arguments);
						console.log("result::", result)
						return result;
					}
				});
			}
		}
	};

	// ajax-post方法
	const post_methods = function(url, data, successFun, errorFun) {
		$.ajax({
			type: "post",
			url: url,
			data: data,
			cache: false,
			dataType: "JSON",
			contentType: "application/json; charset=UTF-8",
			success: function(data) {
				successFun(data)
			},
			error: function(err) {
				errorFun(err)
			}
		})
	};


	T[sdk_name] = new Proxy(_anyPortal, _handler);
})(window);
